/**
 * ---------------------------
 * Time: 2017/8/6 18:28.
 * Author: Cangshi
 * View: http://palerock.cn
 * ---------------------------
 */
define(['app', 'zepto'], function (app, $) {
    app.controller('device-repair', function ($scope, $routeParams, deviceService, Parts, ObjectUtils, DateTimeUtils, RepairRecord, ArrayUtils) {
        // 规定用以管理历史零件记录
        var partsStorage = {
            // 最大历史条目
            maxLength: 50,
            // 默认储存历史零件的记录名
            partsStorageName: 'device_parts_storage_name',
            // 读取历史零件记录
            read: function () {
                var partsStr = localStorage.getItem(this.partsStorageName);
                if (!partsStr) {
                    return null;
                }
                try {
                    this._parts = JSON.parse(partsStr);
                } catch (e) {
                }
                if (!(this._parts instanceof Array)) {
                    this._parts = null;
                }
                return this._parts;
            },
            // 保存单个零件记录
            save: function (parts) {
                if (!this._parts || this._parts.length <= 0) {
                    if (!this.read()) {
                        this._parts = [];
                    }
                }
                var _this = this;
                // 判断欲加入的零件名是否在历史记录中存在
                ArrayUtils.isContainsObject(this._parts, parts, function (i) {
                    // 若存在则删除该记录，并将其置顶
                    _this._parts.splice(i, 1);
                });
                this._parts.unshift(parts);
                if (this._parts.length > this.maxLength) {
                    this._parts.pop();
                }
                localStorage.setItem(this.partsStorageName, JSON.stringify(this._parts));
            }
        };

        // 初始化
        var init = function () {
            // 初始化设备
            var deviceNo = $routeParams.deviceNo;
            if (deviceNo == null) {
                app.backEvent();
            } else {
                // 获取设备信息
                deviceService.getDeviceByDeviceNo(deviceNo, function (device) {
                    $scope.device = device;
                    if (device == null) {
                        app.backEvent();
                    }
                    $scope.$digest();
                });
            }
            // 初始化零件清单
            $scope.partsList = [];
            // 初始化欲添加的零件
            $scope.addingParts = {
                partsNumber: 1
            };
        };
        init();

        /**
         * 显示添加零件的区域（或关闭）
         */
        $scope.showAddingElement = function () {
            var part = $('.new-parts');
            if (part.hasClass('hidden')) {
                part.removeClass('hidden');
                var partsHistory = partsStorage.read();
                // 若有零件的历史记录则在模态列表中显示以供选择
                if (partsHistory && partsHistory instanceof Array && partsHistory.length > 0) {
                    app.openListModel('最近使用过的零件列表', partsStorage.read(), function (partsName) {
                        $scope.addingParts.partsName = partsName;
                        $scope.$digest();
                        part.find('.part-name').trigger('focus');
                    });
                }
                part.find('.part-name').trigger('focus');
            } else {
                part.addClass('hidden');
            }
        };

        /**
         * 添加零件到清单
         */
        $scope.addParts = function () {
            if ($scope.addingParts.partsName == null || $scope.addingParts.partsName == '') {
                $.alert('零件名不能为空');
                return;
            }
            if ($scope.addingParts.partsNumber == null || $scope.addingParts.partsNumber < 1) {
                $.alert('零件数量不能为空或小于等于0');
                return;
            }
            partsStorage.save($scope.addingParts.partsName);
            $scope.addingParts.partsNo = DateTimeUtils.getCurrentId();
            $scope.partsList.push(new Parts($scope.addingParts));
            $('.new-parts').addClass('hidden');
            $scope.addingParts = ObjectUtils.cloneObject({
                partsNumber: 1
            });
        };

        /**
         * 移除清单中的某一零件
         * @param index
         */
        $scope.removeParts = function (index) {
            $scope.partsList.splice(index, 1);
        };

        /**
         * 提交维修清单记录
         */
        $scope.submit = function () {
            if ($scope.recordConsumedTimeDuration == null || $scope.recordConsumedTimeDuration < 0) {
                $.alert('维修时间不能为空或小于0');
                return;
            }
            if ($scope.expenditure == null || $scope.expenditure < 0) {
                $.alert('维修总支出不能为空或小于0');
                return;
            }
            var record = new RepairRecord({
                recordId: DateTimeUtils.getCurrentId(),
                runningDurationBeforeRepair: $scope.device.runningDuration,
                recordConsumedTimeDuration: $scope.recordConsumedTimeDuration,
                recordConsumedMoney: $scope.expenditure,
                recordConsumedParts: $scope.partsList
            });
            $scope.device.repairRecords.unshift(record);
            deviceService.updateDevice($scope.device, function (e) {
                $.alert('添加维修记录成功', function () {
                    history.back();
                });
                $scope.reloadDevices();
            });
        }
    });
});